import Vue from 'vue';
import VueRouter from 'vue-router';
import login from '../views/login.vue';
import signup from '../views/signup.vue';
import main from '../views/main.vue';
import edit from '../views/edit.vue';

Vue.use(VueRouter);

const routes = [
  {
    path: '/',
    name: 'login',
    component: login,
    meta: {
      title: '登录',
      requiresAuth: false,
      index: 1
    }
  },
  {
    path: '/signup',
    name: 'signup',
    component: signup,
    meta: {
      title: '注册',
      requiresAuth: false,
      index: 2
    }
  },
  {
    path: '/main',
    name: 'main',
    component: main,
    meta: {
      title: '主页',
      requiresAuth: true,
      index: 3
    }
  },
  {
    path: '/edit',
    name: 'edit',
    component: edit,
    meta: {
      title: '编辑',
      requiresAuth: true,
      index: 4
    }
  }
];

const router = new VueRouter({
  mode: 'hash',  // 设置为 'hash' 模式
  routes
});

router.beforeEach((to, from, next) => {
  const isLoggedIn = localStorage.getItem('isLoggedIn') === 'true';

  if (to.meta.requiresAuth && !isLoggedIn) {
    next({ name: 'login' });
  } else {
    next();
  }
});

export default router;
